local H = require "packages/new_heg/util"
local HC = require "packages/new_hegcomplements/util"
local U = require "packages/utility/utility"
local extension = Package:new("overseaheg")
extension.extensionName = "new_hegcomplements"
extension.game_modes_whitelist = { 'ex_heg_mode', 'mul_heg_mode' }

Fk:loadTranslationTable {
  ["overseaheg"] = "海外",
  ["os_hc_heg"] = "海外",
}

local tianyu = General(extension, "os_hc_heg__tianyu", "wei", 4)

local zhenxi = fk.CreateTriggerSkill{
  name = "os_hc__zhenxi",
  anim_type = "control",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and
      data.card.trueName == "slash" and data.to then
      return true
    end
    return false
  end,
  on_cost = function(self, event, target, player, data)
    local choices = {}
    local room = player.room
    local target = room:getPlayerById(data.to)
    if not target:isNude() then
      table.insert(choices, "os_hc__zhenxi_discard:" .. target.id)
    end
    table.insert(choices, "os_hc__zhenxi_use:" .. target.id)
    if H.getGeneralsRevealedNum(player) == 2 and H.getGeneralsRevealedNum(target) < 2 then
      table.insert(choices, "beishui_os_hc__zhenxi")
    end
    table.insert(choices, "Cancel")
    local choice = room:askForChoice(player, choices, self.name, nil, false)
    if choice ~= "Cancel" then
      self.cost_data = {tos = {target.id}, choice = choice}
      return true
    end
    return false
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local target = room:getPlayerById(data.to)
    local choice = self.cost_data.choice
    if not choice:startsWith("os_hc__zhenxi_use") and not target:isNude() then
      local cards = room:askForCardsChosen(player, target, 1, 1, "he", self.name)
      room:throwCard(cards, self.name, target, player)
    end
    if not choice:startsWith("os_hc__zhenxi_discard") then
      local success, dat = room:askForUseActiveSkill(player, "#os_hc__zhenxi_vs", "#os_hc__zhenxi-ask:"..target.id,  true, {bypass_distances = true, must_targets = {target.id}})
      if success and dat then
        local card = dat.cards
        local c = Fk:cloneCard(Fk:getCardById(card[1]).suit == Card.Club and "supply_shortage" or "indulgence")
        c.skillName = self.name
        c:addSubcards(card)
        local use = { from = player.id, tos = { dat.targets }, card = c, extra_data = {bypass_distances = true} }
        room:useCard(use)
      end
    end
  end,
}
local zhenxi_vs = fk.CreateViewAsSkill{
  name = "#os_hc__zhenxi_vs",
  handly_pile = true,
  min_card_num = 1,
  max_card_num = 1,
  card_filter = function(self, to_select, selected, player)
    if #selected == 0  then
      local card = Fk:getCardById(to_select)
      if card.type ~= Card.TypeTrick and (card.suit == Card.Club or card.suit == Card.Diamond) then
        local delay = Fk:cloneCard(card.suit == Card.Club and "supply_shortage" or "indulgence")
        delay:addSubcard(to_select)
        return player:canUse(delay, {bypass_distances = true})
      end
    end
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    local c = Fk:cloneCard(Fk:getCardById(cards[1]).suit == Card.Club and "supply_shortage" or "indulgence")
    c.skillName = zhenxi.name
    c:addSubcards(cards)
    return c
  end,
}

local jiansu = fk.CreateTriggerSkill{
  name = "os_hc__jiansu",
  mute = true,
  relate_to_place = "d",
  events = {fk.AfterCardsMove, fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    if event ==  fk.EventPhaseStart then
      if player == target and player.phase == Player.Play then
        local n = #table.filter(player:getCardIds("h"), function (cid)
          return Fk:getCardById(cid):getMark("@@os_hc__jiansu-inhand") > 0
        end)
        return table.find(player.room.alive_players, function (p)
          return p.hp <= n
        end)
      end
    else
      if player.phase ~= Player.NotActive then return end
      local cards = {}
      for _, move in ipairs(data) do
        if move.to == player.id and move.toArea == Card.PlayerHand then
          for _, info in ipairs(move.moveInfo) do
            if table.contains(player:getCardIds("h"), info.cardId)  then
              table.insertIfNeed(cards, info.cardId)
            end
          end
          self.cost_data = cards
          return #cards >0
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event ==  fk.EventPhaseStart then
      local success, dat = room:askForUseActiveSkill(player, "#os_hc__jiansu_active", "#os_hc__jiansu-ask",  true, {skipUse = true})
      if success and dat then
        self.cost_data = {dat.cards, dat.targets}
        return true
      end
    else
      return room:askForSkillInvoke(player, self.name)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if event ==  fk.EventPhaseStart then
      room:notifySkillInvoked(player, self.name, "support", self.cost_data[2])
      room:doIndicate(player.id, self.cost_data[2])
      Fk.skills["#os_hc__jiansu_active"]:onUse(room, {
        from = player.id,
        cards = self.cost_data[1],
        tos = self.cost_data[2],
      })
    else
      local cards = self.cost_data
      room:notifySkillInvoked(player, self.name, "special")
      for _, c in ipairs(cards) do
        room:setCardMark(Fk:getCardById(c), "@@os_hc__jiansu-inhand", 1)
      end
      player:showCards(cards)
    end
  end,
}
local jiansu_visible = fk.CreateVisibilitySkill{
  name = "#os_hc__jiansu_visible",
  frequency = Skill.Compulsory,
  card_visible = function(self, player, card)
    if card and Fk:currentRoom():getCardArea(card) == Card.PlayerHand then
      local owner = Fk:currentRoom():getCardOwner(card)
      if owner and card:getMark("@@os_hc__jiansu-inhand") > 0 then
        return true
      end
    end
  end
}
local jiansu_active = fk.CreateActiveSkill{
  name = "#os_hc__jiansu_active",
  min_card_num = 1,
  target_num = 1,
  card_filter = function (self, to_select, selected, player)
    return Fk:getCardById(to_select):getMark("@@os_hc__jiansu-inhand") > 0
  end,
  target_filter = function(self, to_select, selected, selected_cards, card, extra_data, player)
    if #selected ~= 0 then return end
    local to = Fk:currentRoom():getPlayerById(to_select)
    return to.hp <= #selected_cards and to:isWounded()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:throwCard(effect.cards, self.name, player)
    if not target.dead and target:isWounded() then
      room:recover({
        who = target,
        num = 1,
        recoverBy = player,
        skillName = jiansu.name
      })
    end
  end,
}

tianyu.deputyMaxHpAdjustedValue = -1
zhenxi:addRelatedSkill(zhenxi_vs)
jiansu:addRelatedSkill(jiansu_visible)
jiansu:addRelatedSkill(jiansu_active)
tianyu:addSkill(zhenxi)
tianyu:addSkill(jiansu)

Fk:loadTranslationTable{
  ["os_hc_heg__tianyu"] = "田豫",
  ["#os_hc_heg__tianyu"] = "规略明练",
  ["illustrator:os_hc_heg__tianyu"] = "鬼画府",
  --["designer:os__tianyu"] = "梦魇狂朝 & Loun老萌",

  ["os_hc__zhenxi"] = "震袭",
  [":os_hc__zhenxi"] = "当你使用【杀】指定目标后，你可选择一项：1.弃置其一张牌；2.可将一张<font color='red'>♦</font>/♣非锦囊牌当【乐不思蜀】/【兵粮寸断】对其使用；若其有暗置武将牌且你武将牌均明置，则你可以背水。",
  ["os_hc__jiansu"] = "俭素",
  [":os_hc__jiansu"] = "副将技，此武将牌上单独的阴阳鱼个数-1。当你于回合外获得牌后，你可以明置这些牌。出牌阶段开始时，你可以弃置任意张因此技能明置的手牌，令一名体力值不大于X的角色回复1点体力（X为你以此法弃置的牌数）。",

  ["os_hc__zhenxi_discard"] = "弃置 %src 一张牌",
  ["os_hc__zhenxi_use"] = "对 %src 使用延时锦囊",
  ["beishui_os_hc__zhenxi"] = "背水",
  ["#os_hc__zhenxi-ask"] = "震袭：你可将一张<font color='red'>♦</font>/♣非锦囊牌当【乐不思蜀】/【兵粮寸断】对 %src 使用",
  ["#os_hc__zhenxi_vs"] = "震袭",
  ["@@os_hc__jiansu-inhand"] = "俭素",
  ["#os_hc__jiansu_active"] = "俭素",
  ["#os_hc__jiansu-ask"] = "俭素：你可弃置任意张俭素牌并令一名体力值不小于弃置牌数的角色回复体力",

  ["$os_hc__zhenxi1"] = "戮胡首领，捣其王廷！",
  ["$os_hc__zhenxi2"] = "震疆扫寇，袭贼平戎！",
  ["$os_hc__jiansu1"] = "扬师北疆，剪覆胡奴！",
  ["$os_hc__jiansu2"] = "陈兵百万，慑敌心胆！",
  ["~os_hc_heg__tianyu"] = "钟鸣漏尽，夜行不休……",
}

local sunjian = General(extension, "os_hc_heg__n_sunjian", "wu", 5)

local yinghun = fk.CreateTriggerSkill{
  name = "os_hc__yinghun",
  anim_type = "drawcard",
  mute = true,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start and player:isWounded()
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room:getOtherPlayers(player, false), Util.IdMapper),
    1, 1, "#os_hc__yinghun-choose:::"..player:getLostHp(), self.name, true)
    if #to > 0 then
      self.cost_data = {tos = to}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data.tos[1])
    local n = player:getLostHp()
    local choices = {"#os_hc__yinghun-draw:::" .. n,  "#os_hc__yinghun-discard:::" .. n}
    local choice = (n == 1) and choices[1] or room:askForChoice(player, choices, self.name)
    if choice:startsWith("#os_hc__yinghun-draw") then
      player:broadcastSkillInvoke(self.name, 1)
      room:notifySkillInvoked(player, self.name, "support", {to.id})
      to:drawCards(n, self.name)
      room:askForDiscard(to, 1, 1, true, self.name, false)
    else
      player:broadcastSkillInvoke(self.name, 2)
      room:notifySkillInvoked(player, self.name, "control", {to.id})
      to:drawCards(1, self.name)
      n = player:getLostHp()
      room:askForDiscard(to, n, n, true, self.name, false)
    end
  end,
}
local polu = fk.CreateTriggerSkill{
  name = "os_hc__polu",
  events = {fk.Death},
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.damage and data.damage.from and data.damage.from == player or player:hasSkill(self, false, true) and target == player
  end,
  on_cost = function(self, event, target, player, data)
    local x = player:usedSkillTimes(self.name, Player.HistoryGame) + 1
    local targets = player.room:askForChoosePlayers(player, table.map(player.room.alive_players, Util.IdMapper), 1, x, "#os_hc__polu:::" .. x, self.name, true)
    if #targets > 0 then
      self.cost_data = {tos = targets}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local targets = self.cost_data.tos
    local room = player.room
    room:sortPlayersByAction(targets)
    local x = player:usedSkillTimes(self.name, Player.HistoryGame)
    for _, pid in ipairs(targets) do
      local p = room:getPlayerById(pid)
      if not p.dead then
        p:drawCards(x)
      end
    end
  end,
}
sunjian:addSkill(yinghun)
sunjian:addSkill(polu)

Fk:loadTranslationTable{
  ["os_hc_heg__n_sunjian"] = "孙坚",
  ["#os_hc_heg__n_sunjian"] = "武烈帝",
  ["illustrator:os_hc_heg__n_sunjian"] = "漫想族",

  ["os_hc__yinghun"] = "英魂",
  [":os_hc__yinghun"] = "准备阶段，若你已受伤，你可以选择一名其他角色并选择一项：1.令其摸X张牌，然后弃置一张牌；2.令其摸一张牌，然后弃置X张牌（X为你已损失的体力值）。",
  ["#os_hc__yinghun-choose"] = "英魂：你可以令一名其他角色：摸%arg张牌然后弃置一张牌，或摸一张牌然后弃置%arg张牌",
  ["#os_hc__yinghun-draw"] = "摸%arg张牌，弃置1张牌",
  ["#os_hc__yinghun-discard"] = "摸1张牌，弃置%arg张牌",
  ["os_hc__polu"] = "破虏",
  [":os_hc__polu"] = "当你杀死一名角色时或你死亡时，你可令任意名角色各摸X张牌（X为你发动过此技能的次数+1）。",
  ["#os_hc__polu"] = "破虏：你可选择至多 %arg 名角色，令其各摸 %arg 张牌",

  ["$os_hc__yinghun1"] = "义定四野，武匡海内。",
  ["$os_hc__yinghun2"] = "江东男儿，皆胸怀匡扶天下之志。",
  ["$os_hc__polu1"] = "斩敌复城，扬我江东军威！",
  ["~os_hc_heg__n_sunjian"] = "吾身虽死，忠勇须传。",
}

local liufuren = General(extension, "os_hc_heg__liufuren", "qun", 3, 3, General.Female)

local zhuidu = fk.CreateTriggerSkill{
  name = "os_hc__zhuidu",
  anim_type = "offensive",
  events = {fk.DamageCaused},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_cost = function(self, event, target, player, data)
    self.cost_data = {tos = {data.to.id}}
    return player.room:askForSkillInvoke(player, self.name, data, "#os_hc__zhuidu:"..data.to.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    target = data.to
    local choice = "os_hc__zhuidu-add"
    if target:isFemale() and #room:askForDiscard(player, 1, 1, true, self.name, true, ".", "#os_hc__zhuidu-discard") > 0 then
      choice = "all"
    else
      local choices = {"os_hc__zhuidu-add"}
      if table.find(target:getCardIds("e"), function (c)
        return not target:prohibitDiscard(Fk:getCardById(c))
      end) then
        table.insert(choices, "os_hc__zhuidu-equip")
      end
      choice = room:askForChoice(target, choices, self.name)
    end
    if choice ~= "os_hc__zhuidu-equip" then
      data.damage = data.damage + 1
    end
    if choice ~= "os_hc__zhuidu-add" then
      target:throwAllCards("e")
    end
  end,
}

local shigong = fk.CreateTriggerSkill{
  name = "os_hc__shigong",
  anim_type = "support",
  frequency = Skill.Limited,
  events = {fk.EnterDying},
  can_trigger = function(self, event, target, player, data)
    return player == target and player:hasSkill(self) and player.phase == Player.NotActive and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
      and H.hasGeneral(player, true)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local current = room.current
    local generalname = H.getActualGeneral(player, true)
    H.removeGeneral(room, player, true)
    if current.dead then return end
    local skills = Fk.generals[generalname]:getSkillNameList()
    skills = table.filter(skills, function (s)
      local skill = Fk.skills[s]
      return skill and not skill.lordSkill and skill.frequency <= 2 and skill.relate_to_place == nil and skill.arrayType == nil
        and #skill.attachedKingdom == 0 and not skill:isSwitchSkill()
    end)
    local skill
    if #skills > 0 then
      local result = room:askForCustomDialog(current, self.name,
        "packages/utility/qml/ChooseSkillBox.qml", {
          skills, 0, 1, "#os_hc__shigong"
        })
      if result ~= "" then
        local choice = json.decode(result)
        if #choice > 0 then
          skill = choice[1]
        end
      end
    end
    if skill then
      room:handleAddLoseSkills(current, skill)
      if not player.dead and player.hp < player.maxHp then
        room:recover{
          who = player,
          num = player.maxHp - player.hp,
          recoverBy = player,
          skillName = self.name,
        }
      end
    else
      if not player.dead and player.hp < 1 then
        room:recover{
          who = player,
          num = 1 - player.hp,
          recoverBy = player,
          skillName = self.name,
        }
      end
    end
  end,
}

liufuren:addSkill(zhuidu)
liufuren:addSkill(shigong)

Fk:loadTranslationTable{
  ["os_hc_heg__liufuren"] = "刘夫人",
  ["#os_hc_heg__liufuren"] = "酷妒的海棠",
  ["illustrator:os_hc_heg__liufuren"] = "Jzeo",
  --["designer:liufuren"] = "梦魇狂朝",

  ["os_hc__zhuidu"] = "追妒",
  [":os_hc__zhuidu"] = "出牌阶段内限一次，当你造成伤害时，你可以令受伤角色选择一项：1.此伤害+1；2.弃置装备区里的所有牌（至少一张）；若其为女性角色，则你可以背水：弃置一张牌。",
  ["os_hc__shigong"] = "示恭",
  [":os_hc__shigong"] = "限定技，当你于回合外进入濒死状态时，你可以移除副将，令当前回合者选择一项：1.获得你移除的副将的一个没有技能类型的技能，令你体力回复至体力上限；2.令你体力回复至1点。",

  ["#os_hc__zhuidu"] = "是否对 %src 发动〖追妒〗？",
  ["os_hc__zhuidu-add"] = "此伤害+1",
  ["os_hc__zhuidu-equip"] = "弃置装备区的牌",
  ["#os_hc__zhuidu-discard"] = "是否背水，弃置一张牌？",
  ["#os_hc__shigong"] = "示恭：你可以获得一个技能",

  ["$os_hc__zhuidu1"] = "到了阴司地府，你们也别想好过！",
  ["$os_hc__zhuidu2"] = "髡头墨面，杀人诛心。",
  ["$os_hc__shigong1"] = "冀州安定，此司空之功也……",
  ["$os_hc__shigong2"] = "妾当自缚，以示诚心。",
  ["~os_hc_heg__liufuren"] = "害人终害己，最毒妇人心……",
}

return extension